package com.awanp3.nimbus.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.awanp3.nimbus.common.core.utils.StringUtils;
import com.awanp3.nimbus.demo.domain.DemoTree;
import com.awanp3.nimbus.demo.domain.bo.DemoTreeBo;
import com.awanp3.nimbus.demo.domain.vo.DemoTreeVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.awanp3.nimbus.demo.mapper.DemoTreeMapper;
import com.awanp3.nimbus.demo.service.IDemoTreeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 测试树表Service业务层处理
 *
 * @author 20014170
 * @date 2021-07-26
 */
// @DS("slave") // 切换从库查询
@RequiredArgsConstructor
@Service
public class DemoTreeServiceImpl implements IDemoTreeService {

    private final DemoTreeMapper baseMapper;

    @Override
    public DemoTreeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    // @DS("slave") // 切换从库查询
    @Override
    public List<DemoTreeVo> queryList(DemoTreeBo bo) {
        LambdaQueryWrapper<DemoTree> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DemoTree> buildQueryWrapper(DemoTreeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DemoTree> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTreeName()), DemoTree::getTreeName, bo.getTreeName());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            DemoTree::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.orderByAsc(DemoTree::getId);
        return lqw;
    }

    @Override
    public Boolean insertByBo(DemoTreeBo bo) {
        DemoTree add = BeanUtil.toBean(bo, DemoTree.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(DemoTreeBo bo) {
        DemoTree update = BeanUtil.toBean(bo, DemoTree.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(DemoTree entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
